<{if $goods.spec }>
<script>
/*=规格选择联动=
*(c) shopex.cn
* 2009-2
*/

void function() {

	var buyBtn;
	var notifyBtn;
	var setbuyBtnTip;
	var popAloneSpec=function(){};

	window.addEvent('domready', function() {
		buyBtn = $('goods-viewer').getElement('.btn-buy');
		if (buyBtn) buyBtn.store('tip:text', '');
		notifyBtn = $('goods-viewer').getElement('.btn-notify');
		if (notifyBtn) notifyBtn.store('tip:text', '<{t}>对不起,您当前选择的商品缺货.<{/t}>');
		if (buyBtn) new Tips(buyBtn, {
			showDelay: 0,
			hideDelay: 0,
			className: 'cantbuy',

			onShow: function(tip) {
				if (!tip.getElement('.tip-text') || ! tip.getElement('.tip-text').get('text')) {
					buyBtn.setStyle('cursor', 'pointer');
					return tip.setStyle('visibility', 'hidden');
				} else {
					buyBtn.setStyle('cursor', 'not-allowed');
				}

				tip.setStyle('visibility', 'visible');
			}
		});
		new Tips(notifyBtn, {
			className: 'cantbuy',
			showDelay: 0,
			hideDelay: 0
		});
		if (buyBtn) buyBtn.addEvent('click', function(e) {
			e.stop();
			this.blur();
			if (this.retrieve('tip:text')) return false;
			this.form.submit();
		});
		if (notifyBtn) notifyBtn.addEvent('click', function(e) {
			e.stop();
			this.blur();
             var backup = this.form.action;
             this.form.action=this.form.get('gnotify');
             this.form.submit();
             this.form.action = backup;
			/*new Element('form', {
				method: 'post',
				'action': $(this.form).get('gnotify')
			}).adopt(this.form.toQueryString().toFormElements()).inject(document.body).submit();*/
		});
		if (notifyBtn) notifyBtn.addEvent('onhide', function() {
            if ($(this).getPrevious('.btn-fastbuy')) $(this).getPrevious('.btn-fastbuy').setStyle('visibility', 'visible');
        });

		/*快速购买*/
		var fastbuyBtn = $('goods-viewer').getElement('.btn-fastbuy');
		if (fastbuyBtn) {
			fastbuyBtn.store('tip:text', '').addEvent('click', function(e) {
				e.stop();
				this.blur();
				if (this.retrieve('tip:text')) return false;
				var form = $('fastbuy-form');
				form.empty().adopt($(this.form).toQueryString().toFormElements());
				//return form.submit();
				var _name = this.get('typeBuy') ? this.get('typeBuy') : 'isfastbuy';
				if (this.get('action')) form.action = this.get('action');

				form.adopt(new Element('input', {
					name: _name,
					value: 1,
					type: 'hidden'
				}));

				<{if $env.conf.b2c.site.login_type == 'href' || $env.cookie.MEMBER}>
				return form.submit();
                <{/if}>

                form.fireEvent('submit',e);
            });

            new Tips(fastbuyBtn,{showDelay:0,hideDelay:0,className:'cantbuy',
                   onShow:function(tip){
                      if(!tip.getElement('.tip-text')||!tip.getElement('.tip-text').get('text')){
                          fastbuyBtn.setStyle('cursor','pointer');
                          return tip.setStyle('visibility','hidden');
                      }else{
                          fastbuyBtn.setStyle('cursor','not-allowed');
                      }
                      tip.setStyle('visibility','visible');
                   }
            });
        }

        setbuyBtnTip=function(){
            var spec_item_nocheck=[];
            $$('#goods-spec .spec-item em').each(function(em){
                if(!em.hasClass('check'))spec_item_nocheck.include(em.get('text'));
            });

            if(spec_item_nocheck.length>0){
                $$(buyBtn,fastbuyBtn).store('tip:text','<{t}>请选择：<{/t}>'+spec_item_nocheck.join(','));
            }else{
                $$(buyBtn,fastbuyBtn).store('tip:text','');
            }
            return arguments.callee;
        }();

        popAloneSpec=(function(){
            var specs = $$('#goods-spec .spec-item','#goods-spec div.spec-item .content');

            specs.each(function(si){
                var specs=si.getElements('a[specid]');
                if(!specs.length) return $('goods-viewer').getElement('.hightbox').empty().set('html','<b><{t}>该商品的所有规格货品已下架<{/t}></b>').addClass('note')
                if(specs.length>1) return false;
                if(specs[0].hasClass('selected')||specs[0].hasClass('lock')) return false;
                specs[0].fireEvent('click');
            });
            return arguments.callee;
        })();

        if((btnBar = $('goods-viewer').getElement('.btnBar'))){
            btnBar.setStyle('visibility','visible');
        }
    });


    var getSpecText=function(el){
       if(el.getElement('img'))
       return el.getElement('img').alt||el.getElement('img').title;
       return el.getElement('span').get('text');
    };

    var specItems=$$('#goods-spec .spec-item em');
    var referencePoint={
        bn:$('goodsBn'),
        weight:$('goodsWeight'),
        marketPrice:$('goods-viewer').getElement('.mktprice1'),
        price:$('goods-viewer').getElement('.goodsprice'),
        discount:$('goods-viewer').getElement('.discount'),
        store:$('goods-viewer').getElement('.buyinfo .store'),
        specTip:$('goods-spec') ? $('goods-spec').getElement('.spec-tip') : '',
        update:function(v,html){
           return referencePoint[v]?referencePoint[v].set('html',html):false;
        }
    };
    var RPSV=Object.values(referencePoint);
    RPSV.each(function(el){
         if(el&&typeOf(el)=='element')
         el.retrieve('defaultInnerHTML',el.get('html'));
    });

    var referencePointDef=function(){
        RPSV.each(function(el){
             if(el&&typeOf(el)=='element')
             el.set('html',el.retrieve('defaultInnerHTML'));
        });
        if($('goods-viewer').getElement('.mprice')) $('goods-viewer').getElement('.mprice').hide();
        updatepic();
        if(buyBtn) buyBtn.show();
        if(notifyBtn&&buyBtn) notifyBtn.hide();
    };


    var PRODUCT_HASH=<{if $goods.product2spec}><{$goods.product2spec}><{else}>{}<{/if}>;
    var PRODUCT_SPECV_ARR=[];
        Object.each(PRODUCT_HASH,function(v){
             PRODUCT_SPECV_ARR.push(Object.values(v['spec_private_value_id']));
        });
    var SPEC_HASH=<{if $goods.spec2product}><{$goods.spec2product}><{else}>{}<{/if}>;

    /* var updatepicRequest=new Request.HTML({url:'<{link ctl=product act=goodspics}>',
                                           update:$('goods-viewer').getElement('.goodspic'),
                                           autoCancel:true,
                                           onRequest:function(){
                                            }
                                          });
    相册联动*/
    var updatepic=function(vids){

        if(!vids)return $$('.goods-detail-pic-thumbnail li[img_id]').show();
        vids = vids.split(',');

        var pointer = false;
        $$('.goods-detail-pic-thumbnail li[img_id]').each(function(i){
                  if(vids.contains(i.get('img_id'))){
                      i.style.display = 'block';
                      if(!pointer){
                         i.getElement('a').fireEvent('click',{stop:function(){}});
                         pointer = true;
                      }
                  }else{
                      i.style.display = 'none';
                  }
        });


         /* if(!vids)vids='';
         var pud=$('goods-viewer').getElement('.goodspic').retrieve('picsupdatedelay');
         var put=$('goods-viewer').getElement('.goodspic').retrieve('picsupdatetemp','');
         clearTimeout(pud);
         if(put==vids)return;
         $('goods-viewer').getElement('.goodspic').store('picsupdatedelay',
            (function(){
            updatepicRequest.post({gimages:vids,goodsId:$('goods-viewer').getElement('input[name^=goods[goods_id]').get('value')});
            $('goods-viewer').getElement('.goodspic').store('picsupdatetemp',vids);
            }).delay(800)
         );*/
    };


    /*其他联动*/

    var updateReference=function(specSelected,specvidarr){
          var fix=(specvidarr.length==specItems.length);
          setbuyBtnTip();
          var productIntersection=[];

          /*当前已选择规格的商品交集*/
           var specTip=[];
           var picsId=[];
          if(specSelected){
              specSelected.each(function(s){
                   productIntersection.combine(SPEC_HASH[s.get('specvid')]['product_id']);
                   specTip.include("<font color=red>\""+getSpecText(s)+"\"</font>");
                   picsId.combine(SPEC_HASH[s.get('specvid')]['images']);
              });
          }

          if(!productIntersection||!productIntersection.length)return referencePointDef();

          var price=[];
          productIntersection.each(function(pid){
              var product=PRODUCT_HASH[pid];
              /*if(storeCount.toInt()>9999){
                storeCount='9999+';
              }else{
                storeCount=storeCount.toInt()+product['store'].toInt();
              }*/

              price.include(product['price']).clean();
          });

          /*相册联动*/

          picsId = picsId.clean();
          if(picsId.length){
              updatepic(picsId.join(','));
          }
          /*库存联动
          referencePoint.update('store',storeCount.toInt()>9999?'9999+':storeCount);*/

          /*价格联动*/
          if(price.length>1){
                price.sort(function(p1,p2){
                   p1=p1.toInt();
                   p2=p2.toInt();
                   if(p1>p2)return 1;
                   if(p1==p2)return 0;
                   return -1;
                });
                referencePoint.update('price',priceControl.format(price[0])+'-'+priceControl.format(price[price.length-1]));
          }else{
               if(!parseInt(price[0])) price[0] = 0;
               referencePoint.update('price',priceControl.format(price[0]));
          }

          /*规格选择提示联动*/
          referencePoint.update('specTip','<em><{t}>您已选择：<{/t}></em><span>'+specTip.join("、")+'</span>');


          var product_hiddenInput=$('goods-spec').getElement('input[name^=goods[product_id]').set('disabled',!fix);
          var mprice=$('goods-viewer').getElement('.mprice');


         /*定位到货品*/
          if(fix){
              var fixProductID=null;
              Object.each(PRODUCT_HASH,function(v,k){
                  if(Array.from(Object.values(v['spec_private_value_id'])).combine(specvidarr).length==specvidarr.length){
                      fixProductID=k;
                  }
              });
              if(fixProductID){
                  var fixProduct=PRODUCT_HASH[fixProductID];
                  referencePoint.update('weight',fixProduct['weight']);
                  referencePoint.update('bn',fixProduct['bn']);
                  referencePoint.update('store',fixProduct['store']);
                  referencePoint.update('price',priceControl.format(fixProduct['price']));
                  product_hiddenInput.set('value',fixProductID);


                   /*库存联动*/
                  if(referencePoint['store']&&(referencePoint['store'].get('text').toInt()<1)){
                      <{if !$goods.nostore_sell}>
                      if(buyBtn)
                      buyBtn.hide();
                      <{/if}>

                      if(!notifyBtn)return;
                      notifyBtn.setStyle('display','inline');
                      notifyBtn.getPrevious('.btn-fastbuy')&&notifyBtn.getPrevious('.btn-fastbuy').setStyle('visibility','hidden');
                      return;
                  }

                  if(buynum=$('goods-viewer').getElement('.buyinfo input[type=text]')){
                      buynum.fireEvent('keyup');
                  }

                  /*优惠联动*/

                  if(referencePoint['discount']&&referencePoint['marketPrice']){
                      var dcType={
                          T1:'<{t}>节省<{/t}>',
                          T2:'<{t}>优惠<{/t}>',
                          T3:'<{t}>折<{/t}>'
                      };
                      var _discount=referencePoint['discount'];
                      var _discountValue=_discount.get('text');
                      var fdt=priceControl._format.sign;

                      var _priceValue = fixProduct['price'];

                      var _priceMarketValue = fixProduct['mktprice'];

                      var _priceDiff=_priceMarketValue-_priceValue;
                      if(!(_priceDiff>0))return;
                      if(_discountValue.test(dcType.T2,'i')){
                          referencePoint.update('discount','<{t}>优惠：<{/t}>'+(_priceDiff/_priceMarketValue*100).toFixed(1)+'%');
                      }else if(_discountValue.test(dcType.T3,'i')){
                          referencePoint.update('discount',((1 - _priceDiff / _priceMarketValue)*10).toFixed(1).replace('.','')+'<{t}>折<{/t}>');
                      }else{
                          referencePoint.update('discount','<{t}>节省：<{/t}>'+priceControl.format(_priceDiff));
                      }
                  }

                  /*会员价联动*/
                  if(mprice&&fixProduct['mprice']){
                      mprice.getElements('.mlvprice').each(function(lvp){
                          lvp.set('text',priceControl.format(fixProduct['mprice'][lvp.get('mlv')]));
                      });
                      mprice.show();
                  }
             }

          }else{
             if(mprice&&fixProduct&&fixProduct['mprice'])
             mprice.hide();
          }
          if(buyBtn) buyBtn.show();
          if(notifyBtn) notifyBtn.hide();
    };

    var specSelections=$$('#goods-spec .spec-item a[specvid]');
    specSelections.addEvent('click',function(e){
        e?e.stop():e;
        this.blur();
        var specid=this.get('specid');
        var specvid=this.get('specvid');
        var prt=this.getParent('li.content')||this.getParent('ul');

        if(this.hasClass('lock'))return;
        if(this.hasClass('selected')){
             this.removeClass('selected');
             if(prt.hasClass('content')){
                   var handle=prt.retrieve('handle');
                   handle.getElement('span').set('text','<{t}>请选择<{/t}>').removeClass('select');
                   handle.removeClass('curr');
                   prt.removeClass('content-curr');
             }
             var n=$$('#goods-spec .specItem a.selected').length;
             if(n<=1){
                  specSelections.each(function(s){s.removeClass('lock');});
                  specSelectedCall(specvid,specid,this);
                  specSelections.removeClass('lock');
                  if(!n){referencePointDef();setbuyBtnTip();}
             }
             if(n){
                 specvid=$$('#goods-spec .specItem a.selected')[0].get('specvid');
                 specid=$$('#goods-spec .specItem a.selected')[0].get('specid');
                 specSelectedCall(specvid,specid,this);
             }
              return;
        }
        if(this.getParent('ul').getElement('a.selected')){
           specSelections.each(function(s){
               s.removeClass('lock');
           });
        }
        var tempsel=prt.retrieve('ts',this);
        if(tempsel!=this){tempsel.removeClass('selected')}
        prt.store('ts',this.addClass('selected'));

        if(prt.hasClass('content')){
               var handle=prt.retrieve('handle');
               handle.getElement('span').set('text',getSpecText(this)).addClass('select');
               handle.removeClass('curr');
               prt.removeClass('content-curr');
        }

        specSelectedCall(specvid,specid,this);
        if(e&&e.fireFromProductsList)return;
        popAloneSpec();
    });

    void function(){
        /*下拉方式的规格选择*/
        var specHandles=$$('#goods-spec .spec-item .handle');
        var specContents=$$('#goods-spec .spec-item .content');

        var tempSlipIndex=0;
        var tempCurrentIndex=-1;

        specHandles.each(function(handle,index){
           var content=specContents[index];
           var contentPadding=content.getPadding();
           content.store('handle',handle);
           handle.addEvent('click',function(e){
                if(tempCurrentIndex>=0&&tempCurrentIndex!=index){
                    specHandles[tempCurrentIndex].removeClass('curr');
                    specContents[tempCurrentIndex].removeClass('content-curr');
                 }
                 tempCurrentIndex=index;
                 this.toggleClass('curr');
                 content.toggleClass('content-curr');

           });
        });
    }();
    /*规格点击时call此函数*/

    var specSelectedCall=function(specvid,specid,spec){
        var selectedHS={};
        var specSelected=$$('#goods-spec .spec-item a.selected');
        var specItems=$$('#goods-spec .specItem');

        specItems.each(function(item){
            if(el=item.getElement('a.selected')){
                var key=specExtend.suffix(el.get('specvid'));
                selectedHS[key] = el.get('specvid');
            }
        });

        selectedHS=specExtend.sort(selectedHS);

        var em=(spec.getParent('li.content')&&spec.getParent('li.content').retrieve('handle')||spec.getParent('.spec-item')).getElement('em');
        em[spec.hasClass('selected')?'addClass':'removeClass']('check');
        var specAll=specExtend.init(selectedHS,specvid);

        specSelections.each(function(s){
            if(specAll.indexOf(s.get('specvid'))>-1){
                s.removeClass('lock')
            }else{
                s.addClass('lock');
            }
        });
        if(specSelected&&specSelected.length)
        updateReference(specSelected,Object.values(selectedHS));
    };

    var specExtend={
      sort:function(selectedHS){
          var sortItem=Object.keys(selectedHS).sort();
              var hs={};
              sortItem.each(function(arr){
                  hs[arr]=selectedHS[arr];
          });
          return hs;
      },
      suffix:function(specvid){
          var specsub;
          PRODUCT_SPECV_ARR.each(function(item){
              item.each(function(s,i){
                  if(s==specvid){specsub=i;return;}
              });
          });
          return specsub;
      },
      to_match:function(regExp){
          var to_string=[];
          PRODUCT_SPECV_ARR.each(function(item){
              to_string.include(":"+item.join(':')+":");
          });
          var specSeleted=[];
          to_string.each(function(arr,key){
              if(regExp.test(arr)){specSeleted.include(arr);}
          });
          return specSeleted;
      },
      to_arr:function(str){
          var spec_arr=[];
          str.each(function(item){
              var tmparr=item.split(":");
              tmparr.pop();tmparr.shift();
              spec_arr.include(tmparr);
          });
          return spec_arr;
      },
      merge:function(arr){
          var spec_arr=[];
          arr[0].each(function(e,i){
              var sarr=[];
              arr.each(function(el){
                  sarr.include(el[i]);
              });
              spec_arr.push(sarr);
          });
          return spec_arr;
      },
      collect:function(prearr,arr,hs,key,state){
          var inarr=[];
          var hskeys=Object.keys(hs);
          prearr.each(function(el,index){
              var barr=[],jarr=[];
              if(key!=index&&hskeys.contains(index.toString())&&hskeys.length!=prearr.length&&!state){
                  barr.combine(prearr[index]);
                  barr.combine(arr[index]);
                  inarr.include(barr);
              }else{
                  arr[index].each(function(item){
                      if(el.contains(item)){
                          jarr.include(item);
                      }
                  });
                  inarr.include(jarr);
              }
          });
          inarr[key]=prearr[key];
          return inarr;
      },
      findCall:function(regexp){
          var inSelected=specExtend.to_match(regexp);
          var tmparr=specExtend.to_arr(inSelected);
          return specExtend.merge(tmparr);
      },
      to_find:function(selectedHS,specvid){
          var subReg=":"+Object.values(selectedHS).join(":(\\d+:)*")+":";
          var tpReg = new RegExp(""+subReg.split("(:\\d+:)*")+"");
          var keys=Object.keyOf(selectedHS,specvid);
          var filterArr=[];
          var chs=selectedHS;

          if(Object.keys(selectedHS).length>2){
              delete chs[keys];
              Object.each(chs, function(item,key){
                  var tmphs=chs;
                  Object.each(tmphs,function(value,i){
                      if(key==i){
                          delete tmphs[i];
                          tmphs[keys]=specvid;
                      }
                  });
                  var hs=specExtend.sort(tmphs);
                  filterArr.push(Object.values(hs));
              });
              var sbReg="";
              filterArr.each(function(item,key){
                  var reg=item.join(":(\\d+:)*");
                  sbReg+=":"+reg+":|";
              });
              sbReg=new RegExp(""+sbReg.substr(0,sbReg.length-1)+"");
              if(chs){
                  var loop=arguments.callee;
                  var preStore=loop(chs,Object.values(chs)[0]);
              }
              var sbSpec=specExtend.findCall(sbReg);
              var sbCollect=specExtend.collect(preStore,sbSpec,selectedHS,keys,true);
          }else{
              filterArr=Object.values(selectedHS);
              var sbReg=new RegExp(""+filterArr.join("|")+"");
              var sbCollect=specExtend.findCall(sbReg);
          }
          var tpCollect=specExtend.findCall(tpReg);
          var specs=specExtend.collect(sbCollect,tpCollect,selectedHS,keys);
          if(Object.keys(selectedHS).length==PRODUCT_SPECV_ARR[0].length)specs=sbCollect;
          return specs;
      },
      init:function(selectedHS,specvid){
          if(Object.keys(selectedHS).length>1){
              var specItems=specExtend.to_find(selectedHS,specvid);
              var specArr=specItems.flatten();
          }else{
              var regExp = new RegExp(":"+specvid+":");
              var specSelected=specExtend.to_match(regExp);
              var specItems=specExtend.to_arr(specSelected);
              var specArr=[];
              specItems.each(function(item){specArr.combine(item);});
              var items;
              $$('#goods-spec .specItem').map(function(item,index){
                  if(item.getElements('a').get('specvid').contains(specvid))items=item;
              });
              items=items.getElements('a').get('specvid');
              specArr.combine(items);
          }
          return specArr;
      }
    };


    var fixProductHidden = $('goods-spec').getElement('input[name^=goods[product_id]');
    var gpList=$('goods-products-list').addEvents({
        pop:function(){
			var scroll_lists = this.getElement('.scroll-lists');
            this.setStyles({
                width:$('goods-spec').getSize().x,
                top:$('goods-spec').getPosition().y,
                left:$('goods-spec').getPosition().x,
                display:'block'
            });
            if(scroll_lists.getSize().y>300){

               scroll_lists.setStyles({
                  height:300,
                  'overflow-y':'auto'
               });
            }
            this.getElements('tbody tr').each(function(tr){
                 var fixProductId = fixProductHidden.disabled?false:fixProductHidden.value;
                 if(tr.get('productid') == fixProductId){
                     tr.addClass('selected');
                 }else{
                     tr.removeClass('selected');
                 }
            });

            $(document.body).addEvent('click',function(e){
                   this.fireEvent('unvisible');
                   $(document.body).removeEvent('click',arguments.callee);
            }.bind(this));
        },
        unvisible:function(){
            this.setStyles({
                top:-20000,
                display:'none'
            });
        }
    });

    gpList.getElements('tbody tr').addEvents({
        mouseenter:function(){
            this.addClass('mouseover');
        },
        mouseleave:function(){
            this.removeClass('mouseover');
            this.fireEvent('mouseup');
        },
        mousedown:function(){
            this.addClass('mousedown');
        },
        mouseup:function(){
            this.removeClass('mousedown');
        },
        click:function(){
             this.fireEvent('ischecked');
        },
        ischecked:function(){
            var productId = this.get('productId');
            var productMap = PRODUCT_HASH[productId];
            var specIDarr = Object.values(productMap['spec_private_value_id']);
            $$('#goods-spec .spec-item a.selected').fireEvent('click');

            specIDarr.each(function(s){
                   var specEl=$('goods-spec').getElement('.spec-item a[specvid='+s+']');

                   if(!specEl)return;
                   specEl.fireEvent('click',{stop:function(){},fireFromProductsList:true});
            });
        }
    });
}();
</script>
<{else}>
<script>
    var fastbuyBtn = $('goods-viewer').getElement('.btn-fastbuy');
    if(fastbuyBtn){
        fastbuyBtn.store('tip:text','').addEvent('click',function(e){
             e.stop();
             this.blur();
             if(this.retrieve('tip:text'))return false;
             var form = $('fastbuy-form');

             form.empty().adopt($(this.form).toQueryString().toFormElements());

             var _name = this.get('typeBuy')?this.get('typeBuy'):'isfastbuy';
             if( this.get('action') )  form.action = this.get('action');

             form.adopt(new Element('input', {name:_name,value:1,type:'hidden'}));

             <{if $env.conf.b2c.site.login_type=='href' || $env.cookie.MEMBER}> return form.submit();<{/if}>

             form.fireEvent('submit',e);
        });

        new Tips(fastbuyBtn,{showDelay:0,hideDelay:0,className:'cantbuy',
             onShow:function(tip){
                if(!tip.getElement('.tip-text')||!tip.getElement('.tip-text').get('text')){
                    fastbuyBtn.setStyle('cursor','pointer');
                    return tip.setStyle('visibility','hidden');
                }else{
                    fastbuyBtn.setStyle('cursor','not-allowed');
                }
                tip.setStyle('visibility','visible');
             }
        });
    }
</script>
<{/if}>
<{if $goods.store !== null && $goods.store !== '' && (($goods.store >= 0 && $goods.store < 0.0001) || $goods.store-$goods.freez<=0 || $goods.store-$goods.freez<='0')}>
<script>
    /*无规格商品到货通知 show*/
    window.addEvent('domready',function(){
    // $('goods-viewer').getElement('.btn-fastbuy').set('styles',{'display':'none'});
    // $('goods-viewer').getElement('.btn-buy').set('styles',{'display':'none'});
     var notifyBtn=$('goods-viewer').getElement('.btn-notify');
      if(!notifyBtn)return;
      notifyBtn.store('tip:text','<{t}>您当前要购买的商品暂时缺货,点击进入缺货登记页.<{/t}>');
      new Tips(notifyBtn,{className:'cantbuy',showDelay:0,hideDelay:0});
      notifyBtn.show();
      notifyBtn.removeEvents('click').addEvent('click',function(e){

                e.stop();
                this.blur();
                this.form.action=this.form.get('gnotify');
                this.form.submit();
          });
    });
</script>
<{/if}>
<script>
$$('.addcomment .title input').addEvents({
    'focus':function(){this.removeClass('blur');},
    'blur':function(){this.addClass('blur');}
});
</script>
<{if $goods.status != 'false' }>
<script>
var getStore = function() {
	return $('goods-viewer').getElement('.buy-limit-storess') ? $('goods-viewer').getElement('.buy-limit-storess').get('text').toInt() : $('goods-viewer').getElement('.buyinfo .store').get('text').toInt();
};

var buycoutText = $('goods-viewer').getElement('.buyinfo input[type=text]').addEvents({
    'keydown': function(e) {
        if (!keyCodeFix.contains(e.code)) {
            e.stop();
        }
    },
    'keyup': function(e) {
        if (getStore() < this.value) this.value = getStore();
        if (!this.value || <{if $goods.type.floatstore==='1'}>this.value.toFloat() < 0<{else}>this.value.toInt() < 1<{/if}>) this.value = 1;
    },
    'blur': function(e) {
        if (<{if $goods.type.floatstore==='1'}>this.value.toFloat() <= 0<{else}>this.value.toInt() < 1<{/if}>) this.value = 1;
        <{if $goods.type.floatstore==='1'}>else this.value = this.value.toFloat();<{/if}>
    }
});
/*购买数量调节*/
$$('#goods-viewer .buyinfo .numadjust').addEvent('click', function(e) {
	var countText = $('goods-viewer').getElement('.buyinfo input[name^=goods[num]');
	if (this.hasClass('increase')) {
		countText.set('value', (countText.value.toInt() + 1).limit(1, getStore()));
	} else {
		countText.set('value', (countText.value.toInt() - 1).limit(1, getStore()));
	}
	this.blur();
});

$$('#goods-viewer .buyinfo .numadjust').addEvents({
	'mousedown': function() {
		this.addClass('active');
	},
	'mouseup': function() {
		this.removeClass('active');
	}
});

$$('#goods-viewer .hightline').addEvents({
	mouseenter: function() {
		this.addClass('hightline-enter');
	},
	mouseleave: function() {
		this.removeClass('hightline-enter');
	}
});
</script>
<{if $goods.adjunct && count($goods.adjunct)>0}>
<script>
/*配件JS*/
void function(){
    var updateAdjunctPrice=function(){
        var adjunctPrice=0;

        var selected=$$('#goods-adjunct tr').filter(function(tr,index){
            return tr.getElement('input[type=checkbox]').checked;
        });
        selected.each(function(s,i){
           adjunctPrice+=s.get('price').toFloat()*s.getElement('input[type=hidden]').value.toFloat();
        });
        var price=isNaN(adjunctPrice)?0:adjunctPrice;
        $('goods-adjunct').getElement('.spare-price').set('text',priceControl.format(price));
    };

    var adjunctCheckbox=$$('#goods-adjunct input[type=checkbox]');
    var adjunctText=$$('#goods-adjunct input[type=text]');

    adjunctCheckbox.addEvent('click',function(e){
        var  prt=this.getParent('tr');
        var  min_num=prt.getParent('tbody').get('min_num').toInt();
        if(isNaN(min_num)||min_num<1)min_num=1;

        var _hidden=prt.getElement('input[type=hidden]').set('disabled',!this.checked);

        this.checked?prt.setStyle('background','#F4F4F4'):prt.setStyle('background','#fff');

        var _text=prt.getElement('input[type=text]');

        if(!_text.value||_text.value<min_num){

          _hidden.value=_text.value=min_num;
        }else{
          _hidden.value=_text.value;
        }
        updateAdjunctPrice();

    });

    adjunctText.addEvents({
        'keydown': function(e){
            if(!keyCodeFix.contains(e.code)){
                e.stop();
            }
        },
        'keyup': function(e){
            var prt=this.getParent('tr');
            var min_num=prt.getParent('tbody').get('min_num').toInt();
            var max_num=prt.getParent('tbody').get('max_num').toInt();
            var _hidden=prt.getElement('input[type=hidden]');
            if(isNaN(min_num)||min_num<0){
                min_num=0;
            };
            if(isNaN(max_num)||max_num<0){
                max_num=Number.MAX_VALUE;
            };
            if(this.value){
                _hidden.value=this.value=this.value.toInt().limit(min_num,max_num);
            }
            updateAdjunctPrice();
        }
    });
}();
</script>
<{/if}>
<{/if}>
<script>
    /*设置浏览过的商品*/
    window.addEvent('domready', function(){

        /*Tab的处理*/
        try{
        var viewTabsContainer=$('goods-viewer').getElement('.goods-detail-tab');
        var viewTabs=[];
        var viewSections=$$('#goods-viewer .section');

        viewSections.each(function(se){
        var t=new Element('span',{'class':'goodsDetailTab'}).set('html','<a>'+se.get('tab')+'</a>');
        viewTabs.push(t);
        });

        viewTabsContainer.adopt(viewTabs);
        new Tabs('goods-viewer',{
          panels:'.pdtdetail',
          eventType:'click',
          triggers:'.goodsDetailTab',
          content:'.goodsDetailContent',
          onInit:function(){
              this.panels.each(function(el,i){
                  el.show().getElements('.displaydiv').hide();
                  el.getElements('.allnum').addEvent('click',function(e){
                      this.triggers[i].fireEvent('click');
                      try{this.panels[i].getElement('textarea:enabled').focus();}catch(e){}
                   }.bind(this));
              },this);
          },
          onSwitch:function(index){
              this.panels.each(function(el,i){
                if(!this.activeIndex){
                  el.show().getElements('.displaydiv').hide();
                  el.getElements('.all_link').show();
                }else{
                  if(this.activeIndex!=i)el.hide();
                  el.getElements('.displaydiv').show();
                  el.getElements('.all_link').hide();

                }
              },this);
          }
        });
        }catch(e){}
    });
    /*验证码刷新*/
    function changeimg(id,type){
        if(type == 'discuss'){
            $(id).set('src','<{link app="b2c" ctl="site_comment" act="gen_dissvcode" arg0="s"}>?'+(new Date()));
        }
        else if(type == 'ask'){
            $(id).set('src','<{link app="b2c" ctl="site_comment" act="gen_askvcode" arg0="s"}>?'+(new Date()));
        }
    }
</script>
<script>
withBroswerStore(function(broswerStore){
    broswerStore.get('history',function(history){
        history=JSON.decode(history);
        if(!history||typeOf(history)!=='array')history=[];
        if(history.length==40){history.pop()};
        var newhis={
            'goodsId':<{$goods.goods_id}>,
            'goodsName':'<{$goods.name|replace:"'":"\'"}>',
            'goodsImg':'<{$images.gimages[$goods.image_default].small|storager}>',
            'sortTime': +new Date(),
            'viewTime': +new Date()
        };
        if(!history.some(function(i,index){
            if(i['goodsId']==newhis['goodsId']){
                 history.erase(i);
                 history.include(newhis);
                 return true;
            }
            return false;
        })){history.include(newhis);}

        broswerStore.set('history',history);
    });
});
</script>

<!--<{script src='goodscupcake.js' app='b2c'}>-->
